package com.buddies.lottery.utils;

import android.graphics.Bitmap;
import android.text.TextUtils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.tencent.bugly.crashreport.CrashReport;

import java.util.Hashtable;

public class QRCodeEncoder {

    public static Bitmap encodeQRcode(String url) {
        // 判断URL合法性
        if (TextUtils.isEmpty(url)) {
            return null;
        }

        int width = 640;
        int height = 640;

        Bitmap bitmap = null;
        try {
            // 图像数据转换，使用了矩阵转换
            Hashtable<EncodeHintType, String> hints = new Hashtable<>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            BitMatrix bitMatrix = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, width, height, hints);

            // 逐个生成二维码的图片像素点
            int[] pixels = new int[width * height];
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * width + x] = 0xff000000;
                    } else {
                        pixels[y * height + x] = 0xffffffff;
                    }
                }
            }
            // 生成二维码图片的格式，使用ARGB_8888
            bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        } catch (Throwable e) {
            CrashReport.postCatchedException(e);
        }

        return bitmap;
    }

}
